# import socket
#
# # 创建服务器套接字实例
# server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# # 绑定Ip和端口
# SERVER_INFO = ("192.168.11.157", 60000)
# server_socket.bind(SERVER_INFO)
#
# # 开始侦听
# server_socket.listen()
#
# # 接受客户端的连接
# client_socket, client_addr = server_socket.accept()
# print(client_addr, "连接上了")
#
# # 向客户端发送消息
# send_msg = input("输入发送信息")
# send_bytes = send_msg.encode("gbk")
# client_socket.send(send_bytes)
#
# # 接收客户端消息
# recv_bytes = client_socket.recv(1024)
# recv_msg = recv_bytes.decode("gbk")
# print(f"收到消息", recv_msg)
#
# # 关闭客户端 关闭服务器
# client_socket.close()
# server_socket.close()


# 在主线程中发送消息，
# 需要开辟一个接受客户端连接的线程
# 每一个连接的客户端都需要一个线程专门接受改客户端的消息


import socket
import threading

def t_recv_main(client_socket, clientaddr):
    while True:
        recv_bytes = client_socket.recv(1024)
        if len(recv_bytes) == 0:
            for client in client_list:
                if client[0] == clientaddr[1]:
                    client_list.remove(client)
                    print(f"客户端{clientaddr} 断开了 当前共有客户端{len(client_list)}")
                    break
            break
        recv_msg = recv_bytes.decode("gbk")
        print(f"接受消息 {clientaddr} {recv_msg}")

def t_accept_main(server_socket):
    while True:
        client_socket, clientaddr = server_socket.accept()
        client_list.append([clientaddr[1], client_socket])
        print(f"{clientaddr} 连接了  当前共有客户端{len(client_list)}")
        # 有客户端链接了，就创建线程用来接受他的消息

        t_recv = threading.Thread(target=t_recv_main, args=(client_socket, clientaddr))
        t_recv.start()



# 客户端俩表   [[10001, socket],[10002, socket],[10003,socket]]
client_list = []


def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    SERVER_ADDR = ("192.168.11.157", 60000)
    server_socket.bind(SERVER_ADDR)
    server_socket.listen()
    print(f"服务器启动了")

    # 开启线程 用来反复接受客户端的连接
    t_accept = threading.Thread(target=t_accept_main, args=(server_socket,))
    t_accept.start()

    while True:
        # 先通过端口匹配到目标客户端
        port = input("输入发送客户端的端口")
        port = int(port)
        for client in client_list:
            if client[0] == port:
                send_msg = input("输入发送信息")
                send_bytes = send_msg.encode("gbk")
                client[1].send(send_bytes)
                break
        else:
            print(f"没有找到对应的客户端")

if __name__ == '__main__':
    main()
